package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author 刘昱江
 * 时间 2021/5/11
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public String findUserByUP(User user) {
        String md5pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        QueryWrapper qw = new QueryWrapper();
        qw.eq("username", user.getUsername());
        qw.eq("password", md5pass);
        System.err.println(md5pass);
        if (userMapper.selectList(qw).isEmpty())
            return null;
        else {
            return md5pass;
        }
    }

    @Override
    public PageResult findUserByPage(PageResult pageResult) {
        IPage page=new Page(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper qw=new QueryWrapper();
        qw.like(StringUtils.hasLength(pageResult.getQuery()),"username", pageResult.getQuery());
        IPage iPage = userMapper.selectPage(page, qw);
        long total = iPage.getTotal();
        List<User> list=iPage.getRecords();
        pageResult.setRow(list);
        pageResult.setTotal(total);
        return pageResult;
    }

    @Override
    public Integer updateStatus(Integer id, Boolean status) {
        User user=new User();
        user.setStatus(status);
        QueryWrapper qw=new QueryWrapper();
        qw.eq("id", id);
        return userMapper.update(user,qw);
    }

    @Override
    public Integer insert(User user) {
        user.setPassword( DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setStatus(true);

        return userMapper.insert(user);
    }

    @Override
    public Integer deletebyid(Integer id) {
        return userMapper.deleteById(id);
    }

    @Override
    public Integer update(User user) {
        return userMapper.updateById(user);
    }
}
